package com.healMyself.controller;

import com.healMyself.pojo.User;
import com.healMyself.service.UserService;
import com.healMyself.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/user")
public class UserServlet extends BaseServlet{
    UserService userService = new UserServiceImpl();

    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("开始执行register");
        //获取用户的所有信息
        Map<String, String[]> map = req.getParameterMap();
        //把map中的数据封装到一个一个用户对象
        User u = new User();
        try {
            BeanUtils.populate(u,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        int row = userService.registerUser(u);
        //根据返回值row判断是否添加成功
        if (row > 0){
            req.getRequestDispatcher("/user/login.jsp").forward(req, resp);
        }else {
            throw new RuntimeException("注册失败");
        }
    }


    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取用户输入的信息
        String inputAccount = req.getParameter("account");
        String inputPassword = req.getParameter("password");
        User user = userService.loginUser(inputAccount, inputPassword);
        //判断user是否为空
        if (user != null){
            req.getSession().setAttribute("userObject", user);
//            req.getSession().setAttribute("userId", user.getId());
            resp.sendRedirect("/healmyself/index.jsp");
        }else {
            throw new RuntimeException("未查找到用户");
        }
    }
}
